package com.prim.update.impl;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;

import com.prim.update.listener.OnDownloadListener;
import com.prim.update.model.Progress;

import java.lang.ref.WeakReference;

/**
 * ================================================
 * 作    者：linksus
 * 版    本：1.0
 * 创建日期：3/6 0006
 * 描    述：下载弹窗UI提示
 * 修订历史：
 * ================================================
 */
public class DefaultDownloadUIHandler implements OnDownloadListener {
    private WeakReference<Context> mContext;
    private ProgressDialog mDialog;

    public DefaultDownloadUIHandler(Context mContext) {
        this.mContext = new WeakReference<>(mContext);
    }

    private void createDialog(String msg, int pro) {
        if (mContext.get() instanceof Activity && !((Activity) mContext.get()).isFinishing()) {
            ProgressDialog dialog = new ProgressDialog(mContext.get());
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage(msg);
            if (pro != -1) {
                dialog.setProgress(pro);
            }
            dialog.setIndeterminate(false);
            dialog.setCancelable(false);
            dialog.show();
            mDialog = dialog;
        }
    }

    @Override
    public void onStart() {
        createDialog("下载开始", -1);
    }

    @Override
    public void onProgress(Progress progress) {
        if (mDialog != null) {
            mDialog.setProgress((int) (progress.fraction * 100));
            mDialog.setMessage("下载中:" + (progress.speed / 1024 / 1024) + " M/s");
        } else {
            createDialog("下载中", (int) (progress.fraction * 100));
        }
    }

    @Override
    public void onError(String msg) {
        if (mDialog != null) {
            mDialog.setMessage(msg);
        }
    }

    @Override
    public void onFinish() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }
}
